import 'package:flutter/material.dart';

class CustomTabBar extends StatefulWidget {
  final List<String> tabTitles; // 选项卡标题
  final List<Widget> tabViews;  // 对应选项卡内容
  final Color? indicatorColor;  // 指示器颜色
  final Color? labelColor;      // 选中标签颜色
  final Color? unselectedLabelColor; // 未选中标签颜色
  final double? indicatorWeight; // 指示器厚度
  final EdgeInsetsGeometry? labelPadding; // 标签内边距
  final bool isScrollable;      // 是否可滚动
  final TabController? controller; // 外部控制器
  final ValueChanged<int>? onTabChanged; // 选项卡切换回调

  const CustomTabBar({
    Key? key,
    required this.tabTitles,
    required this.tabViews,
    this.indicatorColor,
    this.labelColor,
    this.unselectedLabelColor,
    this.indicatorWeight = 2.0,
    this.labelPadding,
    this.isScrollable = false,
    this.controller,
    this.onTabChanged,
  }) : super(key: key);

  @override
  _CustomTabBarState createState() => _CustomTabBarState();
}

class _CustomTabBarState extends State<CustomTabBar> with SingleTickerProviderStateMixin {
  late TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = widget.controller ?? 
        TabController(length: widget.tabTitles.length, vsync: this);
    _tabController.addListener(_handleTabChange);
  }

  void _handleTabChange() {
    if (_tabController.indexIsChanging && widget.onTabChanged != null) {
      widget.onTabChanged!(_tabController.index);
    }
  }

  @override
  void dispose() {
    _tabController.removeListener(_handleTabChange);
    // 只有内部创建的controller才需要dispose
    if (widget.controller == null) {
      _tabController.dispose();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        // TabBar部分
        TabBar(
          controller: _tabController,
          tabs: widget.tabTitles.map((title) => Tab(text: title)).toList(),
          indicatorColor: widget.indicatorColor ?? Theme.of(context).primaryColor,
          labelColor: widget.labelColor ?? Theme.of(context).primaryColor,
          unselectedLabelColor: widget.unselectedLabelColor ?? Colors.grey,
          indicatorWeight: widget.indicatorWeight ?? 2.0,
          labelPadding: widget.labelPadding,
          isScrollable: widget.isScrollable,
        ),
        // TabBarView部分
        Expanded(
          child: TabBarView(
            controller: _tabController,
            children: widget.tabViews,
          ),
        ),
      ],
    );
  }
}